using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security;

namespace OpenWaves.EPiServer.AdminTools.LogViewer
{
    public class LogFilePresenter
    {     
        public string Path { get; set; }
        public BinaryUnit DisplayedContentLength { get; set; }

        public LogFilePresenter()
        {
            this.DisplayedContentLength = BinaryUnit.FromBytes(int.MaxValue);
        }

        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
        public string GetContent()
        {
            this.LoadFile();
            if(File==null)
            {
                return null;
            }

            if(File.Size>this.DisplayedContentLength)
            {
                this.WarningMessage = string.Format(CultureInfo.InvariantCulture,
                    TranslateFallback("fileToBig", "File is bigger than {0}. Only last {0} are displayed. To get all file content download it."), DisplayedContentLength);
            }

            try
            {
                return this.File.GetContent(this.DisplayedContentLength);
            }
            catch (SecurityException ex)
            {
                Log.Error(ex, "Error while loading file {0}.", Path);
                this.ErrorMessage = FormatMessage(ex, Path);
                this.Exception = ex;
            }
            catch (IOException ex)
            {
                Log.Error(ex, "Error while loading file {0}.", Path);
                this.ErrorMessage = FormatMessage(ex, Path);
                this.Exception = ex;
            }

            return null;
            
        }

        public Exception Exception{ get; private set;}

        private static string FormatMessage(Exception e, string path)
        {
            return string.Format(CultureInfo.InvariantCulture, 
                TranslateFallback("contentLoadError", "Cannot load file {0}: {1}."), path, e.Message);
        }

        public string ErrorMessage { get; private set; }

        public string WarningMessage { get; private set; }

        public LogFile File { get; private set; }

        private static string TranslateFallback(string key, string fallback)
        {
            return LogViewerPlugin.TranslateConfigurationFallback(key, fallback);
        }

        public void LoadFile()
        {
            if (string.IsNullOrEmpty(Path))
            {
                this.ErrorMessage = TranslateFallback("noFilePath", "File path has not been specified");
                return ;
            }

            IEnumerable<LogDirectory> directories = LogViewerPlugin.GetLogDirectories();

            foreach (LogDirectory directory in directories)
            {
                LogFile tmpFile;
                if (directory.TryGetFile(Path, out tmpFile))
                {
                    this.File = tmpFile;
                    break;
                }
            }

            if (File == null)
            {
                this.ErrorMessage =
                    String.Format(CultureInfo.InvariantCulture,
                        TranslateFallback("fileNotFound", "File {0} not found in log directories ({1})."),
                        Path, directories.Select(d => d.Path).JoinStrings(", "));
            }

            
        }
    }
}